package com.ypy.flexiplug.plugin.prometheus.parse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.ypy.flexiplug.utils.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

public class PrometheusParser<T> implements IPrometheusParser<T> {
    @Override
    public final List<T> parse(String body, Class<T> clz) {
        return this.parsePrometheusQueryRecord(body, HandlerJsonFactory.dynamicParseForDTO(clz));
    }

    @Nullable
    private <T> List<T> parsePrometheusQueryRecord(@NonNull String json, @NonNull BiFunction<JsonObject, Map<String,Object>, T> handler) {

        if (StringUtils.isBlank(json) || null == handler) {
            return new ArrayList<>();
        }

        try {
            JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
            JsonObject data = jsonObject.getAsJsonObject("data");
            JsonArray result = data.get("result").getAsJsonArray();
            List<T> list = new ArrayList<>();
            boolean isRange = false;
            for (int i = 0; i < result.size(); i++) {
                JsonObject elementObj = result.get(i).getAsJsonObject();
                JsonObject metricObj = elementObj.get("metric").getAsJsonObject();
                Map<String,Object> param = new HashMap<>();
                JsonArray value = null;
                if (elementObj.has("value")){
                    value  = elementObj.get("value").getAsJsonArray();
                } else if (elementObj.has("values")) {
                    value = elementObj.get("values").getAsJsonArray();
                    isRange = true;
                }
                param.put("value", value);
                param.put("isRange", isRange);
                T t = handler.apply(metricObj, param);
                list.add(t);
            }
            return list;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }
}
